<script>
import axios from 'axios';
import ConfirmationDialog2 from '../components/ConfirmationDialog2.vue';

export default {
  name: 'IncidentDetail',

  components: {
    ConfirmationDialog2,
  },

  data() {
    return {
      incident: {
        Inc_id: '',
        Opened: '',
        Resolved: '',
        Opened_by: '',
        Priority: '',
        Project: '',
        Short_description: '',
        Description: '',
        Assigned_to: '',
        Assignment_group: '',
        Incident_state: '',
      },
      showDialog: false,
      comments: [],
      newComment: '',
      currentUser: {
        username: localStorage.getItem('username'),
        role: localStorage.getItem('userRole'),
      },
      isLoading: false, // 加载状态
    };
  },

  computed: {
    isLoggedIn() {
      return !!(this.currentUser.username && this.currentUser.role);
    },
  },

  async mounted() {
    await this.fetchIncident();
    await this.fetchComments();
  },

  methods: {
    async fetchIncident() {
      const incId = this.$route.params.incId;
      try {
        const response = await axios.get(`http://localhost:3000/api/incidents/${incId}`);
        this.incident = response.data;

        // 格式化日期
        if (this.incident.Opened) {
          this.incident.Opened = new Date(this.incident.Opened).toISOString().slice(0, 16);
        }
        if (this.incident.Resolved) {
          this.incident.Resolved = new Date(this.incident.Resolved).toISOString().slice(0, 16);
        }
      } catch (error) {
        console.error('获取工单详情失败:', error);
        alert('获取工单详情失败: ' + error.message);
      }
    },

    async fetchComments() {
      try {
        const response = await axios.get(
          `http://localhost:3000/api/incidents/${this.$route.params.incId}/comments`
        );
        this.comments = response.data;
      } catch (error) {
        console.error('获取评论失败:', error);
      }
    },

    async addComment() {
      if (!this.newComment.trim() || !this.isLoggedIn) {
        alert('请先登录后再发表评论');
        return;
      }

      this.isLoading = true; // 显示加载状态

      try {
        let nickname = this.currentUser.username; // 默认使用用户名

        // 尝试获取昵称
        try {
          const nicknameResponse = await axios.post('http://localhost:3000/api/getNickname', {
            username: this.currentUser.username,
            userRole: this.currentUser.role,
          });

          if (nicknameResponse.data.nickname) {
            nickname = nicknameResponse.data.nickname;
          }
        } catch (nicknameError) {
          console.error('获取昵称失败，使用用户名作为默认值:', nicknameError);
        }

        // 拼接评论内容
        const commentWithSignature = `${this.newComment} ——由${nickname}创建`;

        // 提交评论
        const response = await axios.post(
          `http://localhost:3000/api/incidents/${this.$route.params.incId}/comments`,
          {
            comment: commentWithSignature,
            username: this.currentUser.username,
            userRole: this.currentUser.role,
          }
        );

        console.log('Comment response:', response.data);

        // 清空输入框并刷新评论列表
        this.newComment = '';
        await this.fetchComments();
      } catch (error) {
        console.error('添加评论失败:', error);
        alert('添加评论失败: ' + (error.response?.data?.details || error.message));
      } finally {
        this.isLoading = false; // 隐藏加载状态
      }
    },

    formatCommentDate(dateString) {
      return new Date(dateString).toLocaleString();
    },

    showConfirmationDialog() {
      this.showDialog = true;
    },

    async updateIncident() {
      try {
        const formattedIncident = {
          ...this.incident,
          Opened: this.incident.Opened ? new Date(this.incident.Opened).toISOString() : null,
          Resolved: this.incident.Resolved ? new Date(this.incident.Resolved).toISOString() : null,
        };

        await axios.put(
          `http://localhost:3000/api/incidents/${this.incident.Inc_id}`,
          formattedIncident
        );
        alert('Incident 更新成功');
        this.$router.push({ name: 'IncidentOverview' });
      } catch (error) {
        console.error('更新 Incident 失败:', error);
        alert('更新 Incident 失败: ' + (error.response?.data?.message || error.message));
      } finally {
        this.showDialog = false;
      }
    },

    goBack() {
      this.$router.push({ name: 'IncidentOverview' });
    },
  },
};
</script>